import { defineStore } from 'pinia'
import { activeTag, tags, WITHOUT_TAG_PATHS } from './helpers'
import { router } from '@/router'
import { sStorage } from '@/utils'
import type { TagItem } from '@/router/types'

export const useTagsStore = defineStore('tag', {
  state() {
    return {
      tags: tags || ([] as Array<TagItem>),
      activeTag: activeTag || ''
    }
  },
  getters: {
    activeIndex(): number {
      return this.tags.findIndex((item: TagItem) => item.path === this.activeTag)
    }
  },
  actions: {
    setActiveTag(path: string) {
      this.activeTag = path
      sStorage.set('activeTag', path)
    },
    setTags(tags: Array<TagItem>) {
      this.tags = tags
      sStorage.set('tags', tags)
    },
    addTag(tag: TagItem) {
      this.setActiveTag(tag.path)
      if (WITHOUT_TAG_PATHS.includes(tag.path) || this.tags.some((item: TagItem) => item.path === tag.path)) return
      this.setTags([...this.tags, tag])
    },
    removeTag(path: string) {
      if (path === this.activeTag) {
        if (this.activeIndex > 0) {
          router.push(this.tags[this.activeIndex - 1].path)
        } else {
          router.push(this.tags[this.activeIndex + 1].path)
        }
      }
      this.setTags(this.tags.filter((tag: TagItem) => tag.path !== path))
    },
    removeOther(curPath: string) {
      this.setTags(this.tags.filter((tag: TagItem) => tag.path === (curPath || this.activeTag)))
      if (curPath !== this.activeTag) {
        router.push(this.tags[this.tags.length - 1].path)
      }
    },
    removeLeft(curPath: string) {
      const curIndex = this.tags.findIndex((item: TagItem) => item.path === curPath)
      const filterTags = this.tags.filter((_: TagItem, index: number) => index >= curIndex)
      this.setTags(filterTags)
      if (!filterTags.find((item: TagItem) => item.path === this.activeTag)) {
        router.push(filterTags[filterTags.length - 1].path)
      }
    },
    removeRight(curPath: string) {
      const curIndex = this.tags.findIndex((item: TagItem) => item.path === curPath)
      const filterTags = this.tags.filter((_: TagItem, index: number) => index <= curIndex)
      this.setTags(filterTags)
      if (!filterTags.find((item: TagItem) => item.path === this.activeTag)) {
        router.push(filterTags[filterTags.length - 1].path)
      }
    },
    resetTags() {
      this.setTags([])
      this.setActiveTag('')
    }
  }
})
